import { Button, Col, Form, Modal, message, Row, Upload } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import { useState } from 'react';
import { importProductFile } from '@/services/product';
// import { uploadFile } from "@/services/file";
import { gutter } from '../const/keys';

type Props = {
  onClose?: (reflash?: boolean) => void;
};

//成功，失败，待定
export const ColorText = ({
  children,
  type,
}: {
  children: React.ReactNode;
  type: 'error' | 'success' | 'done' | 'uploading' | undefined;
}) => {
  let color = '--ant-color-warning';
  switch (type) {
    case 'error':
      color = '--ant-color-error';
      break;
    case 'success':
      color = '--ant-color-success';
      break;
    case 'done':
      color = '--ant-color-success';
      break;
    case 'uploading':
      color = '--ant-color-processing';
      break;
    default:
      break;
  }
  return <span style={{ color: `var(${color})` }}>{children}</span>;
};

export const getTextByStatus = (status: string | undefined) => {
  switch (status) {
    case 'done':
      return '上传成功';
    case 'error':
      return '上传失败';
    case 'uploading':
      return '上传中';
    default:
      return '待上传';
  }
};
type MyUploadFile = UploadFile & {
  msg?: string;
};

let timer: NodeJS.Timeout;
const App = (props: Props) => {
  const { onClose = () => {} } = props;
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<MyUploadFile[]>([]);
  const [tplFileList, setTplFileList] = useState<MyUploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  const beforeUpload = (file: UploadFile, fileList: UploadFile[]) => {
    const isLt20M = (file.size ?? 0) / 1024 / 1024 < 20;
    if (!isLt20M) {
      message.error(`${file.name} 超过 20MB，已跳过`);
      return Upload.LIST_IGNORE;
    }
    setFileList(fileList);
    setTplFileList(fileList);

    return false; // 阻止 Upload 组件自动上传
  };

  const ok = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择文件！');
      return;
    }
    setUploading(true);
    const results: MyUploadFile[] = [];
    for (const file of fileList) {
      // 跳过已上传成功的文件
      if (file.status === 'done' || file.status === 'error') continue;

      const formData = new FormData();
      formData.append('name', 'file');
      formData.append('file', file as any);
      //设置上传中状态
      results.push({
        status: 'uploading',
        uid: file.uid,
        type: file.type,
        name: file.name,
        size: file.size,
      });
      setTplFileList([...results]);
      try {
        const { data, msg, success } = await importProductFile(formData);
        const index = results.findIndex((f) => f.uid === file.uid);
        // 根据uid 更新results中的状态
        results[index] = {
          ...results[index],
          status: success ? 'done' : 'error',
          msg: data,
        };

        if (success) {
          console.log(`File ${file.name} uploaded successfully.`);
        } else {
          console.error(`File ${file.name} uploaded failed: ${msg}`);
        }
      } catch (err) {
        console.error(err);
        const index = results.findIndex((f) => f.uid === file.uid);
        results[index] = {
          ...results[index],
          status: 'error',
          msg: '上传异常',
        };

        console.error(`File ${file.name} uploaded failed.`);
      }
    }
    setTplFileList(results);
    setUploading(false);
  };

  return (
    <Modal
      open
      title="批量上传"
      width={500}
      onOk={ok}
      confirmLoading={uploading}
      onCancel={() => onClose()}
      footer={false}
    >
      <Form form={form} labelCol={{ span: 4 }}>
        <Form.Item label="下载模板">
          <Row align="middle" justify="start" gutter={[gutter, 0]}>
            <Col>
              <Button type="link" href="/产品导入模板.xlsx">
                下载
              </Button>
            </Col>
            <Col
              style={{
                color: '#AAA',
              }}
            >
              请根据模板的数据格式来准备上传数据
            </Col>
          </Row>
        </Form.Item>

        <Form.Item label="表格上传">
          <Row justify="start" align="middle" gutter={[gutter, 5]}>
            <Col>
              <Row gutter={[gutter, gutter]}>
                <Col span={24}>
                  <Row>
                    <Col span={24}>
                      <Upload
                        disabled={uploading}
                        fileList={[]}
                        beforeUpload={beforeUpload}
                        onChange={() => {
                          clearTimeout(timer);
                          timer = setTimeout(async () => {
                            await ok();
                          }, 100);
                        }}
                        multiple
                        accept=".rar,.zip,.doc,.pdf,.xlsx"
                      >
                        <Button
                          loading={uploading}
                          disabled={uploading}
                          onClick={() => {
                            setFileList([]);
                            setTplFileList([]);
                          }}
                        >
                          选择文件
                        </Button>
                      </Upload>

                      <Col span={24}>
                        <Col
                          style={{
                            color: '#AAA',
                          }}
                        >
                          支持格式：.xls,xlsx，单个文件不超过 20MB
                        </Col>
                      </Col>
                    </Col>
                  </Row>
                </Col>

                <Col span={24}>
                  <Row gutter={[gutter, 10]}>
                    {tplFileList?.map((file, index) => {
                      const { uid, name, msg } = file;
                      //多少M
                      const sizeInMB = (file.size || 0) / 1024 / 1024;
                      const size1 =
                        sizeInMB < 1
                          ? ` (${((file.size || 0) / 1024).toFixed(2)} KB)`
                          : ` (${sizeInMB.toFixed(2)} MB)`;

                      return (
                        <Col span={24} key={uid || index}>
                          <Row wrap={false}>
                            <Col flex={'auto'}>
                              <Row>
                                <Col span={24}>
                                  {name}
                                  {size1}
                                </Col>
                                <Col
                                  span={24}
                                  style={{
                                    color: '#AAA',
                                  }}
                                >
                                  {msg}
                                </Col>
                              </Row>
                            </Col>
                            <Col flex={'100px'}>
                              <Row justify={'end'}>
                                <Col>
                                  <ColorText type={file.status as any}>
                                    {getTextByStatus(file.status)}
                                  </ColorText>
                                </Col>
                              </Row>
                            </Col>
                          </Row>
                        </Col>
                      );
                    })}
                  </Row>
                </Col>
              </Row>
            </Col>
          </Row>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default App;
